var express = require('express');
const conn = require('./../db/db');
const svgCaptcha = require('svg-captcha');
const sms_util = require('./../util/sms_util');
const md5 = require('blueimp-md5');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

let users = {};
/**
 * 获取首页轮播图
 */
router.get('/api/user_info', (req, res) => {
  /*
    const data = require('../data/homecasual');
    res.json({success_code: 200, message: data})
   */

  // console.log(req.session.captcha);

  // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from users_info';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
});


router.get('/api/captcha', (req, res) => {
  // 1. 生成随机验证码
  let captcha = svgCaptcha.create({
      color: true,
      noise: 3,
      ignoreChars: '0o1i',
      size: 4
  });
  // console.log(captcha.text);

  // 2. 保存
  req.session.captcha = captcha.text.toLocaleLowerCase();

  // 3. 返回客户端
  res.type('svg');
  res.send(captcha.data);
});

/*
  手机验证码登录
*/
router.post('/api/login_code', (req, res) => {
    // 1. 获取数据
    const phone = req.body.params.phone;
    const code = req.body.params.code;

    // 2. 验证验证码是否正确
    if (users[phone] !== code) {
        res.json({err_code: 0, message: '验证码不正确!'});
    }

    // 3. 查询数据
    delete  users[phone];

    let sqlStr = "SELECT * FROM users_info WHERE user_phone = '" + phone + "' LIMIT 1";

    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            results = JSON.parse(JSON.stringify(results));
            // console.log(results)
            if (results[0]) {  // 用户已经存在
                // console.log(results[0]);
                req.session.userId = results[0].id;
                // 返回数据给客户端
                res.json({
                    success_code: 200,
                    message: {id: results[0].id, user_name: results[0].user_name, user_phone: results[0].user_phone}
                });
            } else { // 新用户
                const addSql = "INSERT INTO users_info(user_name, user_pwd, user_phone) VALUES (?, ?, ?)";
                const addSqlParams = [phone, phone, phone];
                conn.query(addSql, addSqlParams, (error, results, fields) => {
                    results = JSON.parse(JSON.stringify(results));
                    // console.log(results);
                    if (!error) {
                        req.session.userId = results.insertId;
                        let sqlStr = "SELECT * FROM users_info WHERE id = '" + results.insertId + "' LIMIT 1";
                        conn.query(sqlStr, (error, results, fields) => {
                            if (error) {
                                res.json({err_code: 0, message: '请求数据失败'});
                            } else {
                                results = JSON.parse(JSON.stringify(results));
                                //返回数据给客户端
                                res.json({
                                    success_code: 200,
                                    message: {
                                        id: results[0].id,
                                        user_name: results[0].user_name,
                                        user_phone: results[0].user_phone
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }
    });

});

/**
 * 密码登录
 */
router.post('/api/login_pwd',(req,res)=>{
    // 1. 获取数据
    const user_name = req.body.params.user_name;
    const user_pwd = req.body.params.user_pwd;
    // const user_code = req.body.params.user_code;
    // if(user_code === ''){
    //     res.json({err_code:0, message:'验证码错误'})
    // }
    // console.log(req.body)
    let isPhoneNum = /^1[34578]\d{9}$/;
    if(isPhoneNum.test(user_name)){
        var pwdSql = `SELECT * from users_info WHERE user_phone='${user_name}' and user_pwd='${user_pwd}'`;
    }else{
        var pwdSql = `SELECT * from users_info WHERE user_name='${user_name}' and user_pwd='${user_pwd}'`;
    }
    conn.query(pwdSql, (error, results, fields) => {
        if(error){
            
            throw error;
        }else{
            results = JSON.parse(JSON.stringify(results));
            if(results.length===0){
                res.json({err_code:0, message:'用户未注册或密码错误'});
                return;
            }else{
                res.json({
                    success_code: 200,
                    message: {
                        id: results[0].id,
                        user_name: results[0].user_name,
                        user_phone: results[0].user_phone
                    },
                });
            }

        }
    });

})

/*
  发送验证码短信
*/
router.get('/api/send_code', (req, res) => {
    // 1. 获取手机号码
    let phone = req.query.phone;

    // 2. 随机产生验证码
    let code = sms_util.randomCode(6);
    // console.log(code);

    /* sms_util.sendCode(phone, code, function (success) {
        if (success) {
             users[phone] = code;
             res.json({success_code: 200, message: '验证码获取成功!'});
         } else {
             res.json({err_code: 0, message: '验证码获取失败!'});
         }
     });*/

    // 成功
    setTimeout(() => {
        users[phone] = code;
        res.json({success_code: 200, message: code});
    }, 2000);

    // 失败
    /*setTimeout(()=>{
        res.json({err_code: 0, message: '验证码获取失败!'});
    }, 2000);*/
    // res.json({err_code: 0, message: '验证码获取失败!'});

});

/**
 * 首页水果数据
 */
router.get('/api/goodsLists',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from goods_info';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
})

/**
 * 首页banner接口 
 */
router.get('/api/bannerLists',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from banner_info';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
});

/**
 * 排行数据
 */
router.get('/api/orderLists',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from goods_info ORDER BY goods_hot DESC LIMIT 10';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
})
/**
 * 新鲜水果接口
 */
router.get('/api/freshfruits',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from goods_info WHERE fresh_goods = 1';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
})
/**
 * 水果菜单接口
 */
router.get('/api/fruitsmenu',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from import_fruits';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
})
router.get('/api/fruitsmenu/other',(req,res)=>{
    // 1.1 数据库查询的语句
  let sqlStr = 'SELECT * from import_fruits limit 9';
  // 1.2 执行语句
  conn.query(sqlStr, (error, results, fields) => {
      // console.log(results[0]);
      if (error) {
          res.json({err_code: 0, message: '请求数据失败'});
      } else {
          res.json({success_code: 200, message: results});
      }
  });
})


/**
 * 按水果类别进行查找
 */
router.post('/api/querybycate',(req,res)=>{
    const data = req.body.params.fruitsName;

    let sqlStr = `SELECT * FROM goods_info_main WHERE goods_long_title LIKE '%${data}%'`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            res.json({success_code: 200, message: results});
        }
    });
})
/**
 * 按水果类别进行查找
 */
router.post('/api/querybynew',(req,res)=>{
    const data = req.body.params.fruitsName;

    let sqlStr = `SELECT * FROM goods_info_main WHERE goods_long_title LIKE '%${data}%' ORDER BY is_new DESC`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            res.json({success_code: 200, message: results});
        }
    });
})

router.get('/api/details',(req,res)=>{
    // console.log(req)
    const id = req.query.id;
    let sqlStr = `SELECT * from goods_info_main where goods_id = ${id}`;
    // let sqlStr = `SELECT * from goods_info_main`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            res.json({success_code: 200, message: results});
            // console.log(results)
        }
    });
})

/**
 * 添加商品到购物车
 */
router.post('/api/add_shop_cart', (req, res) => {
    // 2. 获取客户端传过来的商品信息
    let goods_id = req.body.params.goods_id;
    let goods_name = req.body.params.goods_name;
    let thumb_url = req.body.params.thumb_url;
    let price = req.body.params.price;
    let buy_count = 1;
    let is_pay = 0; // 0 未购买 1购买
    let is_checked = 1;
    let price_show = price;
    // 3. 查询数据
    let sql_str = "SELECT * FROM cart WHERE goods_id = '" + goods_id + "' LIMIT 1";
    conn.query(sql_str, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '服务器内部错误!'});
        } else {
            results = JSON.parse(JSON.stringify(results));
            // console.log(results);
            if (results[0]) { // 3.1 商品已经存在
                let buy_count = results[0].buy_count + 1;
                let sql_str = `UPDATE cart SET buy_count =  ${buy_count} WHERE goods_id =  ${goods_id}` ;
                conn.query(sql_str, (error, results, fields) => {
                    if (error) {
                        res.json({err_code: 0, message: '加入购物车失败!'});
                    } else {
                        res.json({success_code: 200, message: '加入购物车成功!'});
                    }
                });
            } else { // 3.2 商品不存在
                let add_sql = "INSERT INTO cart(goods_id, goods_name, thumb_url, price, buy_count, is_pay, is_checked, price_show) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                let sql_params = [goods_id, goods_name, thumb_url, price, buy_count, is_pay, is_checked, price_show];
                conn.query(add_sql, sql_params, (error, results, fields) => {
                    if (error) {
                        res.json({err_code: 0, message: '加入购物车失败!'});
                    } else {
                        res.json({success_code: 200, message: '加入购物车成功!'});
                    }
                });
            }
        }
    });

});
//购物车列表
router.get('/api/cartList',(req, res) => {
    let sqlStr = `SELECT * from cart`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            if(results[0]){
                let priceArr = [];
                if(results[0].is_checked == 0){
                    results[0].price_show = 0
                }
                results.map((item,index)=>{
                    priceArr.push(item.price*item.buy_count*item.is_checked)
                });
                
                let newVal = priceArr.reduce((prev, cur, index, arr)=>{
                    return prev + cur;
                });               
                res.json({success_code: 200, message: results,price:newVal.toFixed(2)});
            }else{
                res.json({success_code: 200, message: results,price:0});
            }
        }
    });
});

//商品是否选中
router.get('/api/isAdd',(req,res)=>{
    const id = req.query.id;
    let sqlStr = `SELECT * from cart where goods_id = ${id}`;
    // let sqlStr = `SELECT * from goods_info_main`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            if(results[0].is_checked == 0){
                let add_sql = `UPDATE cart SET is_checked = 1,price_show = ${results[0].price} WHERE goods_id = ${id}`;
                conn.query(add_sql, (error, results, fields) => {
                    if (error) {
                        res.send({err_code: 0, message: '未知错误!'});
                    } else {
                        res.send({success_code: 200, message: '选择成功!'});
                    }
                });
            }else{
                let add_sql = `UPDATE cart SET is_checked = 0,price_show = 0 WHERE goods_id = ${id}`;
                conn.query(add_sql, (error, results, fields) => {
                    if (error) {
                        res.send({err_code: 0, message: '未知错误!'});
                    } else {
                        res.send({success_code: 200, message: '选择成功!'});
                    }
                });
            }
        }
    });
});
//商品全选
router.get('/api/selectAll',(req, res) => {
    const checkStatus = req.query.checkStatus;
    let sqlStr = `UPDATE cart SET is_checked = ${checkStatus} `;
    if(checkStatus == 0){
        conn.query(sqlStr,(error,result,fields) => {
            if(error){
                res.json({err_code:0,message:"服务器错误"});
            }else{
                res.json({success_code:200,message:"操作成功",price:0});
            }
        })
    }else{
        conn.query(sqlStr,(error,result,fields) => {
            if(error){
                res.json({err_code:0,message:"服务器错误"});
            }else{
                res.json({success_code:200,message:"操作成功"});
            }
        })
    }
})

//商品数量加
router.get('/api/proCountAdd',(req, res) => {
    const id = req.query.id;
    let sqlStr = `select * from cart where goods_id = ${id}` ;
    conn.query(sqlStr, (error,results,fields) => {
        if(error){
            res.json({err_code:0,message:"服务器错误"});
        }else{
            let price = results[0].price;
            let count = results[0].buy_count;
            let addSql = `update cart SET buy_count = ${results[0].buy_count+1} WHERE goods_id = ${id}`;
            conn.query(addSql,(error,results,fields) => {
                if(error){
                    res.json({err_code:0,message:"服务器错误"}); 
                }else{
                    res.json({success_code:200,message:"操作成功"});
                }
            })
        }
    })
});
//商品数量减
router.get('/api/proCountMinus',(req, res) => {
    const id = req.query.id;
    let sqlStr = `select * from cart where goods_id = ${id}` ;
    conn.query(sqlStr, (error,results,fields) => {
        if(error){
            res.json({err_code:0,message:"服务器错误"});
        }else{
            let count = results[0].buy_count
            let addSql = `update cart SET buy_count = ${results[0].buy_count-1} WHERE goods_id = ${id}`;
            conn.query(addSql,(error,results,fields) => {
                if(error){
                    res.json({err_code:0,message:"服务器错误"}); 
                }else{
                    res.json({success_code:200,message:"操作成功",count:count-1});
                }
            })
        }
    })
});

//删除商品
router.get('/api/delFruits',(req,res)=>{
    const id = req.query.id;
    let sqlStr = `DELETE from cart where goods_id = ${id}`;
    // let sqlStr = `SELECT * from goods_info_main`;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '请求数据失败'});
        } else {
            res.json({success_code: 200, message: '操作成功'});
        }
    });
})



module.exports = router;
